package com.cn.lb.interceptor;

import com.cn.lb.support.RibbonFilterContext;
import com.cn.lb.support.RibbonFilterContextHolder;
import com.cn.utils.SaplingConstant;
import feign.RequestInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author: chenyuncong
 * @Date: 2020/3/11 10:06
 * 拦截HttpServletRequest中的header信息 转到 feign 中去
 */
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(feign.RequestTemplate template) {
//        RibbonFilterContext currentContext = RibbonFilterContextHolder.getCurrentContext();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames =  attributes.getRequest().getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = attributes.getRequest().getHeader(name);
                template.header(name, values);

            }
        }

//        String version = currentContext.getAttributes().get(SaplingConstant.SERVICE_VERSION);
//        if (StringUtils.isNotBlank(version)) {
//            template.header(SaplingConstant.SERVICE_VERSION, version);
//
//        }
    }
}
